{% extends "admin/layout.html" %}
{% block title %}门禁设备管理 - {{ system_config.site_name|default('项目管理系统') }}{% endblock %}
{% block content %}
    <div class="container-fluid">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0">
                <i class="fas fa-door-closed me-2"></i>门禁设备管理
            </h1>
            <div>
                <a href="{{ url_for('zktime.device_add') }}" class="btn btn-primary">
                    <i class="fas fa-plus-circle me-2"></i>添加门禁设备
                </a>
            </div>
        </div>

        <!-- 状态提示卡片 -->
        <div class="row mb-4 gx-3">
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="stat-card p-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="text-muted mb-1">设备总数</h5>
                            <h3 class="mb-0">{{ devices|length }}</h3>
                        </div>
                        <div class="icon-circle bg-primary-subtle">
                            <i class="fas fa-door-closed fa-2x text-primary"></i>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-3 col-md-6 mb-3">
                <div class="stat-card p-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="text-muted mb-1">在线设备</h5>
                            <h3 class="mb-0 text-success">
                                {{ devices|selectattr('status', 'equalto', 1)|list|length }}
                            </h3>
                        </div>
                        <div class="icon-circle bg-success-subtle">
                            <i class="fas fa-check-circle fa-2x text-success"></i>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-3 col-md-6 mb-3">
                <div class="stat-card p-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="text-muted mb-1">离线设备</h5>
                            <h3 class="mb-0 text-danger">
                                {{ devices|selectattr('status', 'equalto', 0)|list|length }}
                            </h3>
                        </div>
                        <div class="icon-circle bg-danger-subtle">
                            <i class="fas fa-times-circle fa-2x text-danger"></i>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-3 col-md-6 mb-3">
                <div class="stat-card p-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="text-muted mb-1">故障设备</h5>
                            <h3 class="mb-0 text-warning">
                                {{ devices|selectattr('status', 'equalto', 2)|list|length }}
                            </h3>
                        </div>
                        <div class="icon-circle bg-warning-subtle">
                            <i class="fas fa-exclamation-triangle fa-2x text-warning"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 设备列表表格 -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-bottom">
                <div class="row align-items-center">
                    <div class="col">
                        <h5 class="mb-0">设备列表</h5>
                    </div>
                    <div class="col text-end">
                        <button class="btn btn-sm btn-outline-secondary" id="refreshBtn">
                            <i class="fas fa-sync-alt me-1"></i>刷新状态
                        </button>
                    </div>
                </div>
            </div>

            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="bg-light">
                        <tr>
                            <th style="width: 15%">设备名称</th>
                            <th style="width: 15%">IP地址</th>
                            <th style="width: 10%">端口</th>
                            <th style="width: 10%">协议</th>
                            <th style="width: 12%">状态</th>
                            <th style="width: 10%">最后心跳</th>
                            <th style="width: 8%">重试次数</th>
                            <th style="width: 35%">操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for device in devices %}
                            <tr>
                                <td>
                                    <div class="font-weight-bold text-gray-800">{{ device.name }}</div>
                                    {% if device.description %}
                                        <div class="text-xs text-muted">{{ device.description }}</div>
                                    {% endif %}
                                </td>
                                <td class="text-monospace">{{ device.ip_address }}</td>
                                <td>{{ device.port }}</td>
                                <td>
                                    <span class="badge bg-info">{{ device.protocol }}</span>
                                </td>
                                <td>
                                    {% if device.status == 1 %}
                                        <span class="badge bg-success">
                                            <i class="fas fa-check-circle me-1"></i>在线
                                        </span>
                                    {% elif device.status == 0 %}
                                        <span class="badge bg-danger">
                                            <i class="fas fa-times-circle me-1"></i>离线
                                        </span>
                                    {% else %}
                                        <span class="badge bg-warning">
                                            <i class="fas fa-exclamation-triangle me-1"></i>故障
                                        </span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if device.last_heartbeat %}
                                        <span class="text-xs" title="{{ device.last_heartbeat.strftime('%Y-%m-%d %H:%M:%S') }}">
                                          {{ device.last_heartbeat.strftime('%m-%d %H:%M') }}
                                        </span>
                                    {% else %}
                                        <span class="text-muted text-xs">未收到</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <span class="font-weight-bold {% if device.retry_count > 0 %}text-warning{% endif %}">
                                        {{ device.retry_count }}
                                    </span>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm" role="group">
                                        <a href="{{ url_for('zktime.device_edit', device_id=device.id) }}"
                                           class="btn btn-outline-primary" title="编辑">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="#" class="btn btn-outline-success test-btn"
                                           data-device-id="{{ device.id }}" title="测试连接">
                                            <i class="fas fa-network-wired"></i>
                                        </a>
                                        <form method="POST" action="{{ url_for('zktime.remote_open', device_id=device.id) }}" class="d-inline">
                                            <input type="hidden" name="door_id" value="1">
                                            <button type="submit" class="btn btn-outline-info" title="远程开门">
                                                <i class="fas fa-door-open"></i>
                                            </button>
                                        </form>
                                        <form method="POST" action="{{ url_for('zktime.remote_restart', device_id=device.id) }}" class="d-inline">
                                            <button type="submit" class="btn btn-outline-warning" title="重启设备">
                                                <i class="fas fa-power-off"></i>
                                            </button>
                                        </form>
                                        <form method="POST" action="{{ url_for('zktime.sync_users_to_device', device_id=device.id) }}" class="d-inline sync-users-form">
                                            <button type="button" class="btn btn-outline-dark sync-users-btn" title="同步用户" data-device-id="{{ device.id }}">
                                                <i class="fas fa-user-plus"></i>
                                            </button>
                                        </form>
                                        <form method="POST" action="{{ url_for('zktime.device_delete', device_id=device.id) }}"
                                              class="d-inline" onsubmit="return confirm('确定要删除设备 {{ device.name }} 吗？')">
                                            <button type="submit" class="btn btn-outline-danger" title="删除">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 测试连接模态框 -->
    <div class="modal fade" id="testConnectionModal" tabindex="-1" aria-labelledby="testConnectionModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="testConnectionModalLabel">测试设备连接</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="spinner-border text-primary" role="status" id="testSpinner">
                        <span class="visually-hidden">正在测试...</span>
                    </div>
                    <div id="testResult" class="mt-3"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作结果模态框 -->
    <div class="modal fade" id="operationResultModal" tabindex="-1" aria-labelledby="operationResultModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="operationResultModalLabel">操作结果</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="operationResult">
                    <div class="spinner-border text-primary" role="status" id="operationSpinner">
                        <span class="visually-hidden">正在处理...</span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 同步用户选择模态框 -->
    <div class="modal fade" id="syncUsersModal" tabindex="-1" aria-labelledby="syncUsersModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="syncUsersModalLabel">选择要同步的用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- 搜索区域 -->
                    <div class="row mb-3">
                        <div class="col-md-8">
                            <div class="input-group">
                                <input type="text" class="form-control" id="userSearchInput" placeholder="搜索用户姓名">
                                <button class="btn btn-outline-secondary" type="button" id="userSearchBtn">
                                    <i class="fas fa-search"></i>
                                </button>
                                <button class="btn btn-outline-secondary" type="button" id="userResetBtn" title="重置搜索">
                                    <i class="fas fa-redo"></i>
                                </button>
                            </div>
                        </div>
                        <div class="col-md-4 text-end">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="checkbox" id="selectAllUsers">
                                <label class="form-check-label" for="selectAllUsers">全选本页</label>
                            </div>
                        </div>
                    </div>

                    <!-- 用户列表表格 -->
                    <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                        <table class="table table-hover table-sm">
                            <thead class="sticky-top bg-light">
                            <tr>
                                <th width="50px">
                                    <input type="checkbox" id="selectAllCurrentPage">
                                </th>
                                <th width="80px">用户ID</th>
                                <th>姓名</th>
                                <th>工号</th>
                                <th>卡号</th>
                                <th>部门</th>
                            </tr>
                            </thead>
                            <tbody id="usersList">
                            <!-- 动态加载 -->
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页控件 -->
                    <nav aria-label="用户列表分页" class="mt-3">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <div class="text-muted small" id="paginationInfo">
                                    正在加载...
                                </div>
                            </div>
                            <div class="col-md-6">
                                <ul class="pagination pagination-sm justify-content-end mb-0" id="usersPagination">
                                    <!-- 动态生成分页 -->
                                </ul>
                            </div>
                        </div>
                    </nav>
                </div>
                <div class="modal-footer">
                    <div class="me-auto">
                        <span class="badge bg-primary" id="selectedCount">已选择 0 个用户</span>
                    </div>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmSyncUsers">确认同步</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量存储模态框实例
        let modalInstances = {};

        // 同步用户模态框相关变量
        let currentUserPage = 1;
        let userPageSize = 10;
        let userTotalPages = 0;
        let userTotalCount = 0;
        let userSearchKeyword = '';
        let selectedUserIds = new Set();
        let currentDeviceId = null;

        // 确保Bootstrap JS已加载
        function ensureBootstrapLoaded() {
            if (typeof bootstrap === 'undefined') {
                console.error('Bootstrap未加载，正在重新加载');
                const script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js';
                document.head.appendChild(script);
                return false;
            }
            return true;
        }

        // 初始化模态框 - 简化版本
        function initModal(modalId) {
            if (!ensureBootstrapLoaded()) return null;

            const modalElement = document.getElementById(modalId);
            if (!modalElement) {
                console.error('模态框元素未找到:', modalId);
                return null;
            }

            // 如果已经初始化过，直接返回实例
            if (modalInstances[modalId]) {
                return modalInstances[modalId];
            }

            try {
                const modal = new bootstrap.Modal(modalElement, {
                    backdrop: true,
                    keyboard: true,
                    focus: true
                });

                // 监听隐藏事件，确保正确关闭
                modalElement.addEventListener('hidden.bs.modal', function() {
                    // 重置模态框内容
                    const spinner = modalElement.querySelector('.spinner-border');
                    const result = modalElement.querySelector('#testResult, #operationResult');
                    if (spinner) spinner.style.display = 'block';
                    if (result) result.innerHTML = '';

                    // 确保焦点回到触发元素
                    const triggerBtn = document.activeElement;
                    if (triggerBtn && triggerBtn.classList.contains('test-btn')) {
                        setTimeout(() => triggerBtn.focus(), 100);
                    }
                });

                modalInstances[modalId] = modal;
                return modal;
            } catch (error) {
                console.error('初始化模态框失败:', modalId, error);
                return null;
            }
        }

        // 显示模态框的辅助函数
        function showModal(modalId) {
            const modal = initModal(modalId);
            if (modal) {
                // 先隐藏所有其他模态框
                Object.keys(modalInstances).forEach(id => {
                    if (id !== modalId && modalInstances[id]) {
                        modalInstances[id].hide();
                    }
                });

                // 显示当前模态框
                modal.show();

                // 确保模态框获得焦点
                setTimeout(() => {
                    const modalElement = document.getElementById(modalId);
                    if (modalElement) {
                        const focusable = modalElement.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
                        if (focusable) focusable.focus();
                    }
                }, 50);
            }
        }

        // 加载用户列表
        function loadUsers(page = 1, keyword = '') {
            currentUserPage = page;
            userSearchKeyword = keyword;

            const params = new URLSearchParams({
                page: page,
                per_page: userPageSize,
                keyword: keyword
            });

            // 显示加载状态
            const usersList = document.getElementById('usersList');
            if (usersList) {
                usersList.innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <div class="mt-2 text-muted">正在加载用户列表...</div>
                        </td>
                    </tr>
                `;
            }

            fetch(`/zktime/device/users_list?${params}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    renderUsers(data.users);
                    renderPagination(data.pagination);
                    updateSelectedCount();
                })
                .catch(error => {
                    console.error('加载用户列表失败:', error);
                    const usersList = document.getElementById('usersList');
                    if (usersList) {
                        usersList.innerHTML = `
                            <tr>
                                <td colspan="6" class="text-center py-4 text-danger">
                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                    加载失败: ${error.message}
                                </td>
                            </tr>
                        `;
                    }
                });
        }

        // 渲染用户列表
        function renderUsers(users) {
            const tbody = document.getElementById('usersList');
            if (!tbody) return;

            if (users.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center py-4 text-muted">
                            <i class="fas fa-users me-2"></i>
                            ${userSearchKeyword ? '没有找到匹配的用户' : '暂无用户数据'}
                        </td>
                    </tr>
                `;
                return;
            }

            tbody.innerHTML = users.map(user => `
                <tr>
                    <td>
                        <input type="checkbox" class="user-checkbox" name="user_ids"
                               value="${user.id}" ${selectedUserIds.has(user.id) ? 'checked' : ''}>
                    </td>
                    <td><span class="text-muted">${user.id}</span></td>
                    <td>
                        <div class="fw-bold">${escapeHtml(user.name)}</div>
                    </td>
                    <td>${user.employee_number ? escapeHtml(user.employee_number) : '<span class="text-muted">-</span>'}</td>
                    <td>${user.card_number ? `<code>${escapeHtml(user.card_number)}</code>` : '<span class="text-muted">-</span>'}</td>
                    <td>${user.department ? escapeHtml(user.department) : '<span class="text-muted">-</span>'}</td>
                </tr>
            `).join('');

            // 绑定复选框事件
            tbody.querySelectorAll('.user-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    const userId = parseInt(this.value);
                    if (this.checked) {
                        selectedUserIds.add(userId);
                    } else {
                        selectedUserIds.delete(userId);
                    }
                    updateSelectedCount();
                    updateSelectAllCheckboxes();
                });
            });
        }

        // 渲染分页控件
        function renderPagination(pagination) {
            const paginationEl = document.getElementById('usersPagination');
            const infoEl = document.getElementById('paginationInfo');

            if (!paginationEl || !infoEl) return;

            const { page, pages, total, per_page } = pagination;
            userTotalPages = pages;
            userTotalCount = total;

            // 更新分页信息
            const start = (page - 1) * per_page + 1;
            const end = Math.min(page * per_page, total);
            infoEl.textContent = `显示第 ${start}-${end} 条，共 ${total} 条记录`;
            if (userSearchKeyword) {
                infoEl.textContent += `（搜索: "${userSearchKeyword}"）`;
            }

            // 生成分页HTML
            let paginationHTML = '';

            // 上一页
            paginationHTML += `
                <li class="page-item ${page <= 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" data-page="${page - 1}" aria-label="上一页">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                </li>
            `;

            // 页码
            const showPages = 5;
            let startPage = Math.max(1, page - Math.floor(showPages / 2));
            let endPage = Math.min(pages, startPage + showPages - 1);

            if (endPage - startPage + 1 < showPages) {
                startPage = Math.max(1, endPage - showPages + 1);
            }

            // 第一页和省略号
            if (startPage > 1) {
                paginationHTML += `
                    <li class="page-item">
                        <a class="page-link" href="#" data-page="1">1</a>
                    </li>
                    ${startPage > 2 ? '<li class="page-item disabled"><span class="page-link">...</span></li>' : ''}
                `;
            }

            // 页码
            for (let i = startPage; i <= endPage; i++) {
                paginationHTML += `
                    <li class="page-item ${i === page ? 'active' : ''}">
                        <a class="page-link" href="#" data-page="${i}">${i}</a>
                    </li>
                `;
            }

            // 最后一页和省略号
            if (endPage < pages) {
                paginationHTML += `
                    ${endPage < pages - 1 ? '<li class="page-item disabled"><span class="page-link">...</span></li>' : ''}
                    <li class="page-item">
                        <a class="page-link" href="#" data-page="${pages}">${pages}</a>
                    </li>
                `;
            }

            // 下一页
            paginationHTML += `
                <li class="page-item ${page >= pages ? 'disabled' : ''}">
                    <a class="page-link" href="#" data-page="${page + 1}" aria-label="下一页">
                        <i class="fas fa-chevron-right"></i>
                    </a>
                </li>
            `;

            paginationEl.innerHTML = paginationHTML;

            // 绑定分页点击事件
            paginationEl.querySelectorAll('.page-link').forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const targetPage = parseInt(this.getAttribute('data-page'));
                    if (!isNaN(targetPage) && targetPage !== page) {
                        loadUsers(targetPage, userSearchKeyword);
                    }
                });
            });
        }

        // 更新选中用户数量
        function updateSelectedCount() {
            const selectedCountEl = document.getElementById('selectedCount');
            if (selectedCountEl) {
                selectedCountEl.textContent = `已选择 ${selectedUserIds.size} 个用户`;
            }
        }

        // 更新全选复选框状态
        function updateSelectAllCheckboxes() {
            const selectAllCurrent = document.getElementById('selectAllCurrentPage');
            const checkboxes = document.querySelectorAll('.user-checkbox:not(:disabled)');
            const checkedCount = document.querySelectorAll('.user-checkbox:checked').length;

            if (selectAllCurrent) {
                selectAllCurrent.checked = checkboxes.length > 0 && checkedCount === checkboxes.length;
                selectAllCurrent.indeterminate = checkedCount > 0 && checkedCount < checkboxes.length;
            }
        }

        // HTML转义函数
        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 创建隐藏输入字段
        function createHiddenInput(name, value) {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = name;
            input.value = value;
            return input;
        }

        // 获取CSRF令牌
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // 处理操作请求
        function handleOperation(form, title) {
            const operationTitle = document.getElementById('operationResultModalLabel');
            const operationSpinner = document.getElementById('operationSpinner');
            const operationResult = document.getElementById('operationResult');

            if (operationTitle) operationTitle.textContent = title;
            if (operationSpinner) operationSpinner.style.display = 'block';
            if (operationResult) operationResult.innerHTML = '';

            showModal('operationResultModal');

            fetch(form.action, {
                method: 'POST',
                body: new FormData(form),
                headers: {
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (operationSpinner) operationSpinner.style.display = 'none';
                    if (operationResult) {
                        const alertClass = data.success ? 'alert-success' : 'alert-danger';
                        operationResult.innerHTML = `
                        <div class="alert ${alertClass}">
                            <i class="fas ${data.success ? 'fa-check-circle' : 'fa-exclamation-triangle'} me-2"></i>
                            ${data.message}
                        </div>
                    `;
                    }
                    if(data.success) {
                        setTimeout(() => {
                            const modal = modalInstances['operationResultModal'];
                            if (modal) modal.hide();
                            window.location.reload();
                        }, 1500);
                    }
                })
                .catch(error => {
                    if (operationSpinner) operationSpinner.style.display = 'none';
                    if (operationResult) {
                        operationResult.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            操作失败: ${error.message}
                        </div>
                    `;
                    }
                });
        }

        // 初始化所有模态框和事件监听器
        function initModalHandlers() {
            if (!ensureBootstrapLoaded()) return;

            // 初始化所有模态框
            initModal('testConnectionModal');
            initModal('operationResultModal');
            initModal('syncUsersModal');
            initModal('syncAttendanceModal');

            // 同步用户模态框事件
            const syncUsersModalEl = document.getElementById('syncUsersModal');
            if (syncUsersModalEl) {
                syncUsersModalEl.addEventListener('show.bs.modal', function() {
                    // 重置状态
                    selectedUserIds.clear();
                    userSearchKeyword = '';
                    currentUserPage = 1;

                    // 加载第一页数据
                    loadUsers(1, '');

                    // 清空搜索框
                    const searchInput = document.getElementById('userSearchInput');
                    if (searchInput) searchInput.value = '';
                });
            }

            // 搜索按钮事件
            const userSearchBtn = document.getElementById('userSearchBtn');
            if (userSearchBtn) {
                userSearchBtn.addEventListener('click', function() {
                    const keyword = document.getElementById('userSearchInput')?.value || '';
                    loadUsers(1, keyword.trim());
                });
            }

            // 搜索输入框回车事件
            const userSearchInput = document.getElementById('userSearchInput');
            if (userSearchInput) {
                userSearchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        const keyword = this.value.trim();
                        loadUsers(1, keyword);
                    }
                });
            }

            // 重置搜索按钮
            const userResetBtn = document.getElementById('userResetBtn');
            if (userResetBtn) {
                userResetBtn.addEventListener('click', function() {
                    const searchInput = document.getElementById('userSearchInput');
                    if (searchInput) searchInput.value = '';
                    loadUsers(1, '');
                });
            }

            // 全选当前页
            const selectAllCurrentPage = document.getElementById('selectAllCurrentPage');
            if (selectAllCurrentPage) {
                selectAllCurrentPage.addEventListener('change', function() {
                    const checkboxes = document.querySelectorAll('.user-checkbox:not(:disabled)');
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = this.checked;
                        const userId = parseInt(checkbox.value);
                        if (this.checked) {
                            selectedUserIds.add(userId);
                        } else {
                            selectedUserIds.delete(userId);
                        }
                    });
                    updateSelectedCount();
                });
            }

            // 全选所有页
            const selectAllUsers = document.getElementById('selectAllUsers');
            if (selectAllUsers) {
                selectAllUsers.addEventListener('change', function() {
                    const selectAllCurrent = document.getElementById('selectAllCurrentPage');
                    if (selectAllCurrent) {
                        selectAllCurrent.checked = this.checked;
                        selectAllCurrent.dispatchEvent(new Event('change'));
                    }
                });
            }

            // 处理远程开门表单
            document.querySelectorAll('form[action*="remote_open"]').forEach(form => {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    handleOperation(this, '远程开门');
                });
            });

            // 处理重启设备表单
            document.querySelectorAll('form[action*="restart"]').forEach(form => {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    handleOperation(this, '重启设备');
                });
            });

            // 处理同步用户按钮点击
            document.querySelectorAll('.sync-users-btn').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    currentDeviceId = this.getAttribute('data-device-id');
                    console.log('同步用户按钮被点击，设备ID:', currentDeviceId);

                    showModal('syncUsersModal');
                });
            });

// 处理测试连接按钮
            document.querySelectorAll('.test-btn').forEach(btn => {
                btn.addEventListener('click', async function(e) {
                    e.preventDefault();
                    const deviceId = this.dataset.deviceId;

                    // 获取设备信息
                    const deviceRow = this.closest('tr');
                    const deviceIp = deviceRow.querySelector('td:nth-child(2)').textContent.trim();
                    const devicePort = deviceRow.querySelector('td:nth-child(3)').textContent.trim();
                    const deviceName = deviceRow.querySelector('td:nth-child(1) .font-weight-bold').textContent.trim();

                    const testSpinner = document.getElementById('testSpinner');
                    const testResult = document.getElementById('testResult');

                    if (testSpinner) testSpinner.style.display = 'block';
                    if (testResult) testResult.innerHTML = '';

                    showModal('testConnectionModal');

                    try {
                        // 步骤1: 先检查网络连通性
                        const networkResponse = await fetch(`/zktime/check_network?ip=${encodeURIComponent(deviceIp)}&port=${devicePort}`);
                        const networkData = await networkResponse.json();

                        if (!networkData.success) {
                            if (testSpinner) testSpinner.style.display = 'none';
                            if (testResult) {
                                testResult.innerHTML = `
                        <div class="alert alert-warning">
                            <i class="fas fa-network-wired me-2"></i>
                            ${networkData.message}<br>
                            <small class="mt-1 d-block">请检查：<br>
                            • 设备电源是否开启<br>
                            • 网络线缆是否连接<br>
                            • 防火墙设置<br>
                            • IP地址和端口是否正确</small>
                        </div>
                    `;
                            }
                            return;
                        }

                        // 步骤2: 网络正常，测试设备连接
                        const response = await fetch(`/zktime/device/${deviceId}/test`, {
                            method: 'POST',
                            headers: {
                                'X-CSRFToken': getCookie('csrftoken'),
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: `device_id=${deviceId}`
                        });

                        const data = await response.json();

                        if (testSpinner) testSpinner.style.display = 'none';
                        if (testResult) {
                            const alertClass = data.success ? 'alert-success' : 'alert-danger';
                            const iconClass = data.success ? 'fa-check-circle' : 'fa-exclamation-triangle';

                            let additionalInfo = '';
                            if (data.success) {
                                additionalInfo = `
                        <div class="mt-2 small text-success">
                            <i class="fas fa-check me-1"></i>
                            设备 ${deviceName} 连接正常，可以执行开门、重启等操作
                        </div>
                    `;
                            } else {
                                additionalInfo = `
                        <div class="mt-2 small text-muted">
                            <i class="fas fa-lightbulb me-1"></i>
                            可能的解决方案：<br>
                            • 检查设备通信密码是否正确<br>
                            • 确认设备型号支持COM连接<br>
                            • 重启设备后重试<br>
                            • 联系系统管理员
                        </div>
                    `;
                            }

                            testResult.innerHTML = `
                    <div class="alert ${alertClass}">
                        <i class="fas ${iconClass} me-2"></i>
                        <strong>${data.message}</strong>
                        ${additionalInfo}
                    </div>
                `;
                        }

                    } catch (error) {
                        if (testSpinner) testSpinner.style.display = 'none';
                        if (testResult) {
                            testResult.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        测试连接时发生错误：${error.message}
                        <div class="mt-2 small text-muted">
                            请检查浏览器控制台获取详细错误信息
                        </div>
                    </div>
                `;
                        }
                        console.error('测试连接错误:', error);
                    }
                });
            });

            // 确认同步用户
            const confirmSyncUsers = document.getElementById('confirmSyncUsers');
            if (confirmSyncUsers) {
                confirmSyncUsers.addEventListener('click', function() {
                    if (selectedUserIds.size === 0) {
                        alert('请至少选择一个用户');
                        return;
                    }

                    console.log('选中的用户ID:', Array.from(selectedUserIds));
                    console.log('当前设备ID:', currentDeviceId);

                    const form = document.querySelector(`.sync-users-form [data-device-id="${currentDeviceId}"]`)?.closest('form');

                    if (!form) {
                        console.error('未找到对应的表单，设备ID:', currentDeviceId);
                        alert('系统错误：未找到对应的设备表单');
                        return;
                    }

                    // 清除之前添加的用户参数
                    form.querySelectorAll('input[name="user_ids[]"]').forEach(el => el.remove());

                    // 添加选中的用户ID
                    selectedUserIds.forEach(userId => {
                        form.append(createHiddenInput('user_ids[]', userId.toString()));
                    });

                    const modal = modalInstances['syncUsersModal'];
                    if (modal) modal.hide();

                    handleOperation(form, '同步用户');
                });
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 刷新状态按钮
            const refreshBtn = document.getElementById('refreshBtn');
            if (refreshBtn) {
                refreshBtn.addEventListener('click', function() {
                    const originalText = this.innerHTML;
                    const originalState = this.disabled;

                    // 显示加载状态
                    this.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>检查设备状态...';
                    this.disabled = true;

                    // 添加一个小延迟让用户看到状态变化
                    setTimeout(() => {
                        window.location.reload();
                    }, 800);

                    // 防止重复点击
                    setTimeout(() => {
                        this.innerHTML = originalText;
                        this.disabled = originalState;
                    }, 3000);
                });
            }

            // 初始化所有模态框和事件监听器
            initModalHandlers();
        });
    </script>
{% endblock %}